<template>
  <div class="app-container">
    <!-- 派工对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备" prop="deviceId">
              <el-select v-model="formData.deviceId" placeholder="请输入设备名称进行搜索" filterable style="width: 100%" remote
                         :remote-method="deviceRemoteMethod" :loading="deviceLoading" @change="handleDeviceChange">
                <el-option v-for="device in deviceList" :key="device.id" :label="device.deviceName" :value="device.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量" prop="workOrderQuantity">
              <el-input v-model.number="formData.workOrderQuantity" placeholder="请输入数量" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划开始日期" prop="planBeginTime">
              <el-date-picker clearable v-model="formData.planBeginTime" type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="选择计划开始日期" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划结束日期" prop="planEndTime">
              <el-date-picker clearable v-model="formData.planEndTime" type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="选择计划结束日期" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="每日派工数量" prop="daySendWorkNumber">
              <el-input v-model.number="formData.daySendWorkNumber" placeholder="请输入每日派工数量" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 报工对话框 -->
    <el-dialog title="报工" :visible.sync="reportDialogVisible" width="600px" append-to-body>
      <el-form ref="reportFormRef" :model="reportFormData" :rules="reportFormRules" v-loading="reportFormLoading"
               label-width="120px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="报工数量" prop="reportQuantity">
              <el-input v-model.number="reportFormData.reportQuantity" placeholder="请输入报工数量" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="批次号" prop="batchNo">
              <el-input v-model="reportFormData.batchNo" placeholder="请输入批次号" :disabled="!!pageInfo.batchNo"
                        style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="排班" prop="scheduleId">
              <el-select v-model="reportFormData.scheduleId" placeholder="请选择排班" filterable style="width: 100%" remote
                         :remote-method="scheduleRemoteMethod" :loading="scheduleLoading">
                <el-option v-for="schedule in scheduleList" :key="schedule.id"
                           :label="schedule.scheduleDate + '-' + schedule.shiftName" :value="schedule.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="报工人" prop="reportUserId">
              <el-select
                v-model="reportFormData.reportUserId"
                placeholder="请选择报工人"
                filterable
                style="width: 100%;"
                remote
                :remote-method="userRemoteMethod"
                :loading="userLoading"
              >
                <el-option v-for="user in userList" :key="user.id" :label="user.nickname" :value="user.id"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitReportForm" :disabled="reportFormLoading">确 定</el-button>
        <el-button @click="reportDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 投料对话框 -->
    <el-dialog title="投料" :visible.sync="feedingDialogVisible" width="600px" append-to-body>
      <el-form ref="feedingFormRef" :model="feedingFormData" :rules="feedingFormRules" v-loading="feedingFormLoading"
               label-width="120px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="物料" prop="materialId">
              <el-select v-model="feedingFormData.materialId" placeholder="请输入物料名称搜索" filterable style="width: 100%"
                         remote
                         :remote-method="materialRemoteMethod" :loading="materialLoading"
                         @change="handleMaterialSelect">
                <el-option v-for="material in materialList" :key="material.materialId" :label="material.materialName"
                           :value="material.materialId"/>
              </el-select>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="24">-->
          <!--            <el-form-item label="基本单位" prop="basicUnit">-->
          <!--              <el-input v-model="feedingFormData.basicUnit" placeholder="单位" style="width: 100%" disabled/>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="24">
            <el-form-item label="投料数量" prop="feedingQuantity">
              <el-input v-model.number="feedingFormData.feedingQuantity" placeholder="请输入投料数量" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="批次号" prop="batchNo">
<!--              <el-input v-model="feedingFormData.batchNo" placeholder="请输入批次号" style="width: 100%"/>-->
              <el-select v-model="feedingFormData.batchNo" placeholder="请选择批次号" filterable style="width: 100%">
                <el-option v-for="material in batchNoList" :key="material.id" :label="material.batchNumber"
                           :value="material.batchNumber">
                  <span style="float: left">{{ material.batchNumber }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">数量：{{ material.quantity }}</span>


                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
<!--          <el-col :span="24">-->
          <!--            <el-form-item label="仓库" prop="warehouseId">-->
          <!--              <treeselect-->
          <!--                v-model="feedingFormData.warehouseId"-->
          <!--                :options="warehouseTree"-->
          <!--                :normalizer="normalizerW"-->
          <!--                placeholder="选择仓库"-->
          <!--                style="width: 100%"-->
          <!--                @select="onWarehouseChange"-->
          <!--              />-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!--          <el-col :span="24">-->
          <!--            <el-form-item label="仓位" prop="storageId">-->
          <!--              <el-select v-model="feedingFormData.storageId" placeholder="请选择仓位" clearable style="width: 100%">-->
          <!--                <el-option v-for="location in locationList" :key="location.id" :label="location.storageLocationName"-->
          <!--                           :value="location.id"/>-->
          <!--              </el-select>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFeedingForm" :disabled="feedingFormLoading">确 定</el-button>
        <el-button @click="feedingDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 顶部操作按钮区域 -->
    <div class="button-container">
      <!--      0-待开始1-执行中2-暂停3-已完成-->
      <el-button type="primary" icon="el-icon-document" style="margin-right: 10px;">SOP查看</el-button>
      <el-button type="primary" icon="el-icon-video-play" style="margin-right: 10px;" v-if="pageInfo.status == 0"
                 @click="doIssued">
        开工
      </el-button>
      <el-button type="primary" :icon="pageInfo.status === 2 ? 'el-icon-video-play' : 'el-icon-video-pause'"
                 style="margin-right: 10px;" @click="doPaused">
        {{ pageInfo.status === 2 ? '继续' : '暂停' }}
      </el-button>
      <el-button type="primary" icon="el-icon-edit" style="margin-right: 10px;" @click="openReportForm">报工</el-button>
      <el-button type="primary" icon="el-icon-receiving" style="margin-right: 10px;" @click="openFeedingForm">投料
      </el-button>
      <el-button type="primary" icon="el-icon-circle-check" style="margin-right: 10px;" @click="doQuality">首检
      </el-button>
      <el-button type="danger" icon="el-icon-switch-button" style="margin-right: 10px;" @click="doFinished">强制完结
      </el-button>

    </div>

    <!-- 工单信息区域 -->
    <div class="info-body">
      <div class="info-cil">
        <div class="info-title">工单号</div>
        <div class="info-param">{{ pageInfo.workOrderNo || '--' }}</div>
      </div>
      <div class="info-cil">
        <div class="info-title">产品名称</div>
        <div class="info-param">{{ pageInfo.productName || '--' }}</div>
      </div>
      <div class="info-cil">
        <div class="info-title">总数</div>
        <div class="info-param">{{ pageInfo.workOrderQuantity || '--' }}</div>
      </div>
      <div class="info-cil">
        <div class="info-title">已完成数量</div>
        <div class="info-param">{{ pageInfo.completeQuantity || '--' }}</div>
      </div>
    </div>
    <div class="info-body">
      <div class="info-cil">
        <div class="info-title">计划号</div>
        <div class="info-param">{{ pageInfo.planNo || '--' }}</div>
      </div>
      <div class="info-cil">
        <div class="info-title">设备名称</div>
        <div class="info-param">{{ pageInfo.deviceName || '--' }}</div>
      </div>
      <div class="info-cil">
        <div class="info-title">状态</div>
        <div class="info-param">{{ getDictDataLabel(DICT_TYPE.WORKORDER_STATUS, pageInfo.status) }}</div>
      </div>
      <div class="info-cil">
        <div class="info-title">每日派工数量</div>
        <div class="info-param">{{ pageInfo.daySendWorkNumber || '--' }}</div>
      </div>
    </div>


    <div class="info-body">
      <div class="info-cil">
        <div class="info-title">计划开始时间</div>
        <div class="info-param">{{ pageInfo.planBeginTime || '--' }}</div>
      </div>
      <div class="info-cil">
        <div class="info-title">计划结束时间</div>
        <div class="info-param">{{ pageInfo.planEndTime || '--' }}</div>
      </div>
      <div class="info-cil">
        <div class="info-title">实际开始时间</div>
        <div class="info-param">{{ pageInfo.actualBeginTime || '--' }}</div>
      </div>
      <div class="info-cil">
        <div class="info-title">实际结束时间</div>
        <div class="info-param">{{ pageInfo.actualEndTime || '--' }}</div>
      </div>
    </div>

    <!-- 报工列表 -->
    <div class="quality-inspection-section">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>报工信息</span>
          </div>
        </template>
        <el-table :data="reportWorkList" style="width: 100%" max-height="300px">
          <el-table-column prop="reportTime" label="报工时间" align="center"/>
          <el-table-column prop="reportQuantity" label="报工数量" align="center"/>
          <el-table-column prop="batchNo" label="批次号" align="center"/>
          <el-table-column prop="shiftName" label="班次" align="center"/>
          <el-table-column prop="reportUserName" label="报工人" align="center"/>
        </el-table>
        <div v-if="reportWorkTotal > 0" class="pagination-container">
          <el-pagination
            background
            layout="prev, pager, next, jumper"
            :total="reportWorkTotal"
            :page-size="reportWorkQueryParams.pageSize"
            :current-page="reportWorkQueryParams.pageNo"
            @current-change="handleReportWorkCurrentChange"
            @size-change="handleReportWorkSizeChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 投料列表 -->
    <div class="quality-inspection-section">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>投料信息</span>
          </div>
        </template>
        <el-table :data="feedingList" style="width: 100%" max-height="300px">
          <el-table-column prop="materialName" label="物料名称" align="center"/>
          <el-table-column prop="feedingQuantity" label="投料数量" align="center"/>
          <el-table-column prop="batchNo" label="批次号" align="center"/>
          <el-table-column prop="feedingTime" label="投料时间" align="center"/>
          <el-table-column prop="basicUnit" label="单位" align="center"/>
          <el-table-column prop="warehouseName" label="仓库" align="center"/>
          <el-table-column prop="storageLocationName" label="仓位" align="center"/>
          <el-table-column prop="feedingUserName" label="投料人" align="center"/>
        </el-table>
        <div v-if="feedingTotal > 0" class="pagination-container">
          <el-pagination
            background
            layout="prev, pager, next, jumper"
            :total="feedingTotal"
            :page-size="feedingQueryParams.pageSize"
            :current-page="feedingQueryParams.pageNo"
            @current-change="handleFeedingCurrentChange"
            @size-change="handleFeedingSizeChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 质检相关假表格 -->
    <div class="quality-inspection-section">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>质检信息</span>
          </div>
        </template>
        <el-table :data="qualityInspectionList" style="width: 100%" max-height="300px">
          <el-table-column label="质检任务单号" align="center" prop="taskNo" width="200" show-overflow-tooltip/>
          <el-table-column label="质检来源类型" align="center" prop="sourceTypeName" width="180">
            <template v-slot="scope">
              {{ getDictDataLabel(DICT_TYPE.QUALITY_SOURCE_TYPE, scope.row.sourceType) }}
            </template>
          </el-table-column>
          <el-table-column label="来源单号" align="center" prop="sourceNo" width="200" show-overflow-tooltip/>
          <el-table-column label="物料编码" align="center" prop="materialNo" width="150" show-overflow-tooltip/>
          <el-table-column label="物料名称" align="center" prop="materialName" width="150" show-overflow-tooltip/>
          <el-table-column label="工序编号" align="center" prop="procedureCode"/>
          <el-table-column label="工序名称" align="center" prop="procedureName" width="150" show-overflow-tooltip/>
          <el-table-column label="质检方案编码" align="center" prop="schemeCode" width="150" show-overflow-tooltip/>
          <el-table-column label="质检方案名称" align="center" prop="schemeName" width="150" show-overflow-tooltip/>
          <el-table-column label="质检方式" align="center" prop="schemeMethod">
            <template v-slot="scope">
              {{ getDictDataLabel(DICT_TYPE.SCHEME_METHOD, scope.row.schemeMethod) }}
            </template>
          </el-table-column>
          <el-table-column label="质检类型" align="center" prop="schemeType">
            <template v-slot="scope">
              {{ getDictDataLabel(DICT_TYPE.SCHEME_TYPE, scope.row.schemeType) }}
            </template>
          </el-table-column>
          <el-table-column label="质检总数" align="center" prop="totalQuantity"/>
          <el-table-column label="合格率" align="center" prop="passRate"/>
          <el-table-column label="合格数量" align="center" prop="passQuantity"/>
          <el-table-column label="不合格数量" align="center" prop="failQuantity" width="120"/>
          <el-table-column label="不合格率" align="center" prop="failRate"/>
          <el-table-column label="不合格原因" align="center" prop="schemeTaskRemark" width="120"/>
          <el-table-column label="返工数量" align="center" prop="reworkQuantity"/>
          <el-table-column label="报废数量" align="center" prop="scrapQuantity"/>
          <el-table-column label="让步接收数量" align="center" prop="compromiseQuantity" width="120"/>
          <el-table-column label="审核报废数量" align="center" prop="auditorScrapQuantity" width="120"/>
          <el-table-column label="审核合格数量" align="center" prop="auditorPassQuantity" width="120"/>
          <el-table-column label="审核人名称" align="center" prop="auditorName" width="120"/>
          <el-table-column label="审核备注" align="center" prop="auditorRemark" width="120"/>
          <el-table-column label="有效状态" align="center" prop="effectiveStatus">
            <template v-slot="scope">
              {{ getDictDataLabel(DICT_TYPE.COMMON_STATUS, scope.row.effectiveStatus) }}
            </template>
          </el-table-column>
          <el-table-column label="无效原因" align="center" prop="invalidReason"/>
          <el-table-column label="备注" align="center" prop="remark"/>
        </el-table>
        <div v-if="qualityInspectionTotal > 0" class="pagination-container">
          <el-pagination
            background
            layout="prev, pager, next, jumper"
            :total="qualityInspectionTotal"
            :page-size="qualityInspectionQueryParams.pageSize"
            :current-page="qualityInspectionQueryParams.pageNo"
            @current-change="handleQualityInspectionCurrentChange"
            @size-change="handleQualityInspectionSizeChange"
          />
        </div>
      </el-card>
    </div>


    <!-- 首检弹窗 -->
    <el-dialog
      title="首检"
      :visible.sync="qualityDialogVisible"
      width="600px"
    >
      <el-form label-width="100px">
        <el-form-item label="质检方案">
          <el-select v-model="selectedInspectionSchemeId" placeholder="请选择质检方案" filterable style="width: 100%">
            <el-option
              v-for="item in firstQualityList"
              :key="item.inspectionSchemeId"
              :label="item.inspectionSchemeName"
              :value="item.inspectionSchemeId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveQuality" >确 定</el-button>
        <el-button @click="qualityDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listDept} from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import * as PlanApi from '@/api/production/plan';
import * as WorkOrderApi from '@/api/production/workorder';
import * as ReportworkApi from '@/api/production/reportwork';
import * as UserApi from '@/api/system/user';
import * as Feeding from '@/api/production/workorderfeeding';
import * as DeviceApi from '@/api/system/device';
import * as ScheduleApi from '@/api/system/schedule';
import * as MaterialApi from '@/api/basic/material/index.js';
import * as WarehouseApi from '@/api/storage/warehouse';
import * as LocationApi from '@/api/storage/location';
import {getWorkOrder, issued} from "@/api/production/workorder";
import {createReportWork} from "@/api/production/reportwork";
import * as ProcessRouteProcessNodeQualityApi from '@/api/basic/processrouteprocessnodequality/index.js';
import * as InspectionSchemeTaskApi from '@/api/quality/inspectionschemetask';
import * as ProcessRouteProcessNodeMaterialApi from "@/api/basic/processrouteprocessnodematerial";
import * as sMaterialApi from '@/api/storage/material';

export default {
  name: "Detail",
  components: {
    Treeselect
  },
  data() {
    return {
      batchNoList: [],
      pageId: null,
      deptList: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产计划列表
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      checkedIds: [],
      nodeList: [],
      // 激活的标签页ID
      activeName: '',
      // 工作订单列表
      workOrderList: [],
      // 对话框相关
      dialogVisible: false,
      dialogTitle: '派工',
      formLoading: false,
      // 表单数据
      formData: {
        id: undefined,
        pageId: null,
        processRouteNodeId: undefined,
        deviceId: undefined,
        deviceName: undefined,
        workOrderQuantity: undefined,
        planBeginTime: undefined,
        planEndTime: undefined,
        daySendWorkNumber: 0
      },
      // 设备列表
      deviceList: [],
      // 设备加载状态
      deviceLoading: false,
      // 表单验证规则
      formRules: {
        deviceId: [{required: true, message: '设备不能为空', trigger: 'blur'}],
        workOrderQuantity: [{required: true, message: '数量不能为空', trigger: 'blur'}]
      },
      // 报工表单相关
      reportDialogVisible: false,
      reportFormLoading: false,
      reportFormData: {
        workOrderId: null,
        reportQuantity: '',
        batchNo: '',
        scheduleId: null,
        reportStatus: 1,
        reportUserId: null,
        reportUserName: null
      },
      // 用户列表
      userList: [],
      // 用户加载状态
      userLoading: false,
      reportFormRules: {
        reportQuantity: [{required: true, message: '报工数量不能为空', trigger: 'blur'}],
        batchNo: [{required: true, message: '批次号不能为空', trigger: 'blur'}],
        scheduleId: [{required: true, message: '排班不能为空', trigger: 'change'}],
        reportUserId: [{required: true, message: '请选择报工人', trigger: 'blur'}]
      },
      scheduleList: [],
      scheduleLoading: false,
      // 投料表单相关
      feedingDialogVisible: false,
      feedingFormLoading: false,
      // 首检弹窗相关
      qualityDialogVisible: false,
      selectedInspectionSchemeId: '',
      feedingFormData: {
        workOrderId: null,
        workOrderNo: '',
        materialId: null,
        basicUnit: '',
        feedingQuantity: 0,
        batchNo: '',
        storageId: null,
        warehouseId: null
      },
      feedingFormRules: {
        materialId: [{required: true, message: '物料不能为空', trigger: 'change'}],
        feedingQuantity: [{required: true, message: '投料数量不能为空', trigger: 'blur'}],
        batchNo: [{required: true, message: '批次号不能为空', trigger: 'blur'}],
        warehouseId: [{required: true, message: '仓库不能为空', trigger: 'change'}],
        storageId: [{required: true, message: '仓位不能为空', trigger: 'change'}]
      },
      // 物料相关
      materialList: [],
      materialLoading: false,
      // 仓库相关
      warehouseTree: [],
      locationList: [],
      // 报工列表相关
      reportWorkList: [],
      reportWorkTotal: 0,
      reportWorkQueryParams: {
        pageNo: 1,
        pageSize: 10,
        workOrderId: null
      },
      // 投料列表相关
      feedingList: [],
      feedingTotal: 0,
      feedingQueryParams: {
        pageNo: 1,
        pageSize: 10,
        workOrderId: null
      },
      pageInfo: {},
      firstQualityList: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        planNo: null,
        deptId: null,
        deptName: null,
        productId: null,
        productName: null,
        productCode: null,
        processRouteId: null,
        processRouteName: null,
        routeType: null,
        routeTypeName: null,
        planBeginTime: [],
        planEndTime: [],
        actualBeginTime: [],
        actualEndTime: [],
        status: null,
        createTime: [],
      },
      // 工单信息项
      workOrderInfoItems: [
        {label: '状态', value: '进行中'},
        {label: '工单号', value: 'WO202405200001'},
        {label: '设备名称', value: '数控车床CK6140'},
        {label: '总数', value: '1000'},
        {label: '已完成数量', value: '350'},
        {label: '计划开始时间', value: '2024-05-20 08:00:00'},
        {label: '计划结束时间', value: '2024-05-25 18:00:00'},
        {label: '实际开始时间', value: '2024-05-20 08:00:00'},
        {label: '实际结束时间', value: '-'}
      ],
      // 质检相关数据
      qualityInspectionList: [],
      qualityInspectionTotal: 0,
      qualityInspectionQueryParams: {
        pageNo: 1,
        pageSize: 10,
        sourceNo: null
      },
    };
  },
  created() {
    // 初始加载时从路由获取pageId
    this.updatePageData();
    // this.getOptions();
  },
  watch: {
    // 监听路由参数变化，确保每次切换工单时更新数据
    '$route.query.id': {
      immediate: true,
      handler(newId) {
        if (newId) {
          this.pageId = newId;
          this.updateDataAfterGetList();
        }
      }
    }
  },
  methods: {
    // 获取质检列表
    async getqualityList() {
      try {
        this.qualityInspectionQueryParams.sourceNo = this.pageInfo.workOrderNo;
        const res = await InspectionSchemeTaskApi.getInspectionSchemeTaskPage(this.qualityInspectionQueryParams);
        this.qualityInspectionList = res.data.list || [];
        this.qualityInspectionTotal = res.data.total || 0;
      } catch (error) {
        console.error('获取质检列表失败:', error);
        this.qualityInspectionList = [];
        this.qualityInspectionTotal = 0;
      }
    },

    // 质检列表页码变化
    handleQualityInspectionCurrentChange(val) {
      this.qualityInspectionQueryParams.pageNo = val;
      this.getqualityList();
    },

    // 质检列表每页数量变化
    handleQualityInspectionSizeChange(val) {
      this.qualityInspectionQueryParams.pageSize = val;
      this.getqualityList();
    },
    // 更新页面数据
    updatePageData() {
      if (this.$route.query.id) {
        this.pageId = this.$route.query.id;
        this.updateDataAfterGetList();
      }
    },

    // 确保getList执行完后再调用其他方法
    async updateDataAfterGetList() {
      await this.getList();
      // getReportWorkList和getFeedingList在getList内部已调用，这里只需要调用getqualityList
      await this.getqualityList();
    },
    // 暂停，继续
    doPaused() {
      WorkOrderApi.paused(this.pageId).then(response => {
        this.$message({
          message: '操作成功',
          type: 'success'
        });
        this.getList();
      });
    },
    // 开工
    doIssued() {
      WorkOrderApi.issued(this.pageId).then(response => {
        this.$message({
          message: '开工成功',
          type: 'success'
        });
        this.getList();
      });
    },
    normalizer(node) {
      // 构建基础对象，确保包含 id, label, children 属性
      // 关键：如果不是第三级节点，则禁用
      return {
        id: node.id,
        label: node.name,
        children: node.children, // 必须包含 children
      };
    },
    getOptions() {
      listDept().then(response => {
        this.deptList = this.handleTree(response.data, "id")[0].children;
      });
    },
    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        const res = await WorkOrderApi.getWorkOrder(this.pageId);
        this.pageInfo = res.data
        // 加载报工列表
        await this.getReportWorkList();
        // 加载投料列表
        await this.getFeedingList();
        // 加载质检列表
        await this.getqualityList();
      } finally {
        this.loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 添加/修改操作 */
    // 打开派工对话框
    async openForm(id) {
      this.dialogVisible = true;
      this.deviceRemoteMethod('')
      this.resetForm();
      // 初始化表单数据，设置当前选中的工艺节点ID和计划ID
      this.formData.processRouteNodeId = this.queryParams.processRouteNodeId;
      this.formData.pageId = this.queryParams.pageId;
      // 加载设备列表
    },

    // 设备远程搜索方法
    async deviceRemoteMethod(query) {
      this.deviceLoading = true;
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          deviceName: query,
        };
        const response = await DeviceApi.getDevicePage(params);
        this.deviceList = response.data.list;
      } catch (error) {
        console.error('搜索设备失败', error);
        this.deviceList = [];
      } finally {
        this.deviceLoading = false;
      }
    },

    // 处理设备选择
    handleDeviceChange(deviceId) {
      const selectedDevice = this.deviceList.find(device => device.id === deviceId);
      if (selectedDevice) {
        this.formData.deviceName = selectedDevice.deviceName;
      } else {
        this.formData.deviceName = undefined;
      }
    },

    // 重置表单
    resetForm() {
      this.formData = {
        id: undefined,
        pageId: this.queryParams.pageId,
        processRouteNodeId: this.queryParams.processRouteNodeId,
        deviceId: undefined,
        deviceName: undefined,
        workOrderQuantity: undefined,
        planBeginTime: undefined,
        planEndTime: undefined,
        daySendWorkNumber: 0
      };
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
    },

    // 打开报工弹框
    openReportForm() {
      this.reportDialogVisible = true;
      this.resetReportForm();
      // 设置工单ID
      this.reportFormData.batchNo = this.pageInfo.batchNo
      this.reportFormData.workOrderId = this.pageId;
      // 默认获取排班列表和用户列表
      this.scheduleRemoteMethod('');
      this.getUserList();
    },

    // 重置报工表单
    resetReportForm() {
      this.reportFormData = {
        workOrderId: this.pageId,
        reportQuantity: '',
        batchNo: '',
        scheduleId: null,
        reportStatus: 1,
        reportUserId: null,
        reportUserName: null
      };
      if (this.$refs.reportFormRef) {
        this.$refs.reportFormRef.resetFields();
      }
      this.getUserList();
    },

    /** 获取用户列表 */
    async getUserList() {
      try {
        const params = {
          pageNo: 1,
          pageSize: 20
        };
        const response = await UserApi.listUser(params);
        this.userList = response.data.list;
      } catch (error) {
        console.error('获取用户列表失败', error);
        this.userList = [];
      }
    },

    // 用户远程搜索方法
    async userRemoteMethod(query) {
      this.userLoading = true;
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          nickname: query
        };
        const response = await UserApi.listUser(params);
        this.userList = response.data.list;
      } catch (error) {
        console.error('搜索用户失败', error);
        this.userList = [];
      } finally {
        this.userLoading = false;
      }
    },

    // 排班远程搜索方法
    async scheduleRemoteMethod(query) {
      this.scheduleLoading = true;
      try {
        const params = {
          pageNo: 1,
          pageSize: 100
        };
        // 如果有查询条件，可以根据需要添加
        if (query) {
          // 可以根据实际需求添加搜索条件
        }
        const response = await ScheduleApi.getSchedulePage(params);
        this.scheduleList = response.data.list || [];
      } catch (error) {
        console.error('搜索排班失败', error);
        this.scheduleList = [];
      } finally {
        this.scheduleLoading = false;
      }
    },

    // 提交报工表单
    async submitReportForm() {
      // 校验表单
      await this.$refs.reportFormRef.validate();
      this.reportFormLoading = true;
      try {
        const data = {...this.reportFormData};

        // 更新报工人名称
        const selectedUser = this.userList.find(user => user.id === data.reportUserId);
        if (selectedUser) {
          data.reportUserName = selectedUser.nickname;
        }

        // 这里应该调用报工的API，暂时使用模拟的方法
        // 实际项目中需要替换为真实的报工API
        console.log('提交报工数据:', data);
        await ReportworkApi.createReportWork(data);
        this.$message({
          message: '报工成功',
          type: 'success'
        });
        this.reportDialogVisible = false;
        // 重新加载列表
        await this.getList();
      } catch (error) {
        console.error('报工失败', error);
      } finally {
        this.reportFormLoading = false;
      }
    },
    async doQuality() {
      const response = await ProcessRouteProcessNodeQualityApi.getQualityAllByNodeId({nodeId: this.pageInfo.processRouteNodeId});
      if (response.code === 0 && response.data) {
        this.firstQualityList = response.data.firstQualityList || [];
        // 打开弹窗
        this.qualityDialogVisible = true;
        this.selectedInspectionSchemeId = '';
      }
    },

    async saveQuality() {
      if (!this.selectedInspectionSchemeId) {
        this.$message.warning('请选择质检方案');
        return;
      }

      try {
        const info = this.pageInfo
        // 构造请求数据（先写死，后续用户自己匹配）
        const data = {
          sourceNo: info.workOrderNo,
          sourceType: 2,
          inspectionSchemeId: this.selectedInspectionSchemeId,
          materialId: info.materialId,
          materialNo: info.materialNo,
          materialName: info.materialName,
          schemeMethod: 1,
          schemeType: 1,
          totalQuantity: info.workOrderQuantity,
          status: 1
        };

        const response = await InspectionSchemeTaskApi.createInspectionSchemeTask(data);
        if (response.code === 0) {
          this.$message.success('创建成功');
          this.qualityDialogVisible = false;
        } else {
        }
      } catch (error) {
      }
    },
    // 打开投料弹框
    async openFeedingForm() {
      this.feedingDialogVisible = true;
      this.resetFeedingForm();
      // 设置工单ID和工单号
      this.feedingFormData.workOrderId = this.pageId;
      this.feedingFormData.workOrderNo = this.pageInfo.workOrderNo || '';
      // 加载仓库树数据
      await this.getWarehouseTree();
      // 默认获取物料列表
      await this.getMaterialList();
    },

    // 重置投料表单
    resetFeedingForm() {
      this.feedingFormData = {
        workOrderId: this.pageId,
        workOrderNo: this.pageInfo.workOrderNo || '',
        materialId: null,
        basicUnit: '',
        feedingQuantity: null,
        batchNo: '',
        storageId: null,
        warehouseId: null
      };
      if (this.$refs.feedingFormRef) {
        this.$refs.feedingFormRef.resetFields();
      }
      this.locationList = [];
    },

    // 获取物料列表方法，默认获取前50条
    async getMaterialList() {
      // this.pageInfo.processRouteNodeId
      try {
        this.materialLoading = true;
        const params = {
          pageNo: 1,
          pageSize: 50
        };
        const res = await ProcessRouteProcessNodeMaterialApi.getMaterialAllByNodeId({nodeId: this.pageInfo.processRouteNodeId});
        this.materialList = res.data.inMaterialList;
      } catch (error) {
        console.error('获取物料列表失败:', error);
        this.materialList = [];
      } finally {
        this.materialLoading = false;
      }
    },

    // 物料远程搜索方法
    async materialRemoteMethod(query) {
      if (query) {
        this.materialLoading = true;
        try {
          const params = {
            pageNo: 1,
            pageSize: 100,
            materialName: query
          };
          const res = await MaterialApi.getMaterialPage(params);
          this.materialList = res.data.list;
        } catch (error) {
          console.error('获取物料列表失败:', error);
          this.materialList = [];
        } finally {
          this.materialLoading = false;
        }
      } else {
        // 如果查询条件为空，默认显示前50条
        await this.getMaterialList();
      }
    },

    // 物料选择后处理
    async handleMaterialSelect(materialId) {
      // 查找选中的物料信息
      // const selectedMaterial = this.materialList.find(m => m.id === materialId);
      // if (selectedMaterial) {
      //   this.feedingFormData.basicUnit = selectedMaterial.unit || '';
      // } else {
      //   this.feedingFormData.basicUnit = '';
      // }
      const code = this.materialList.find(item => item.materialId === materialId).materialNo
      const res = await sMaterialApi.getMaterialPage({
        materialCode: code,
        pageNo: 1,
        pageSize: 100,
        materialState: 1
      });
      this.feedingFormData.batchNo = null
      this.batchNoList = res.data.list
    },

    // 获取仓库树数据
    async getWarehouseTree() {
      try {
        const params = {
          pageNo: 1,
          pageSize: 1000 // 获取足够多的数据用于构建树
        };
        const res = await WarehouseApi.getWarehousePage(params);
        this.warehouseTree = res.data;
      } catch (error) {
        console.error('获取仓库树数据失败:', error);
        this.warehouseTree = [];
      }
    },

    // 树节点标准化处理
    normalizerW(node) {
      const normalizedNode = {
        id: node.id,
        label: node.warehouseName,
        // 只有当children存在且不为空数组时才传递children属性
        children: node.children && node.children.length > 0 ? node.children : undefined
      };
      return normalizedNode;
    },

    // 仓库选择变化时触发
    async onWarehouseChange(warehouseId) {
      this.feedingFormData.storageId = null;
      if (warehouseId) {
        await this.getLocationList(warehouseId.id || warehouseId);
      } else {
        this.locationList = [];
      }
    },

    // 根据仓库ID获取库位列表
    async getLocationList(warehouseId) {
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          warehouseId: warehouseId
        };
        const res = await LocationApi.getLocationPage(params);
        this.locationList = res.data.list;
      } catch (error) {
        console.error('获取库位列表失败:', error);
        this.locationList = [];
      }
    },

    // 提交投料表单
    async submitFeedingForm() {
      // 校验表单
      await this.$refs.feedingFormRef.validate();
      this.feedingFormLoading = true;
      try {
        const data = this.feedingFormData;
        console.log('提交投料数据:', data);
        // 调用投料API
        await Feeding.createWorkOrderFeeding(data);
        this.$message({
          message: '投料成功',
          type: 'success'
        });
        this.feedingDialogVisible = false;
        // 重新加载列表
        await this.getList();
        // 重新加载投料列表
        await this.getFeedingList();
      } catch (error) {
        console.error('投料失败', error);
        this.$message.error('投料失败，请重试');
      } finally {
        this.feedingFormLoading = false;
      }
    },

    // 获取报工列表
    async getReportWorkList() {
      try {
        this.reportWorkQueryParams.workOrderId = this.pageId;
        const res = await ReportworkApi.getReportWorkPage(this.reportWorkQueryParams);
        this.reportWorkList = res.data.list || [];
        this.reportWorkTotal = res.data.total || 0;
      } catch (error) {
        console.error('获取报工列表失败:', error);
        this.reportWorkList = [];
        this.reportWorkTotal = 0;
      }
    },

    // 报工列表页码变化
    handleReportWorkCurrentChange(val) {
      this.reportWorkQueryParams.pageNo = val;
      this.getReportWorkList();
    },

    // 报工列表每页数量变化
    handleReportWorkSizeChange(val) {
      this.reportWorkQueryParams.pageSize = val;
      this.getReportWorkList();
    },

    // 获取投料列表
    async getFeedingList() {
      try {
        this.feedingQueryParams.workOrderId = this.pageId;
        const res = await Feeding.getWorkOrderFeedingPage(this.feedingQueryParams);
        this.feedingList = res.data.list || [];
        this.feedingTotal = res.data.total || 0;
      } catch (error) {
        console.error('获取投料列表失败:', error);
        this.feedingList = [];
        this.feedingTotal = 0;
      }
    },

    // 投料列表页码变化
    handleFeedingCurrentChange(val) {
      this.feedingQueryParams.pageNo = val;
      this.getFeedingList();
    },

    // 投料列表每页数量变化
    handleFeedingSizeChange(val) {
      this.feedingQueryParams.pageSize = val;
      this.getFeedingList();
    },

    // 提交表单
    async submitForm() {
      // 校验表单
      await this.$refs.formRef.validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 调用更新工作订单方法
        await WorkOrderApi.createWorkOrder(data);
        this.$modal.msgSuccess("派工成功");
        this.dialogVisible = false;
        // 重新加载列表
        this.getList();
      } catch (error) {
        console.error('派工失败', error);
        this.$modal.msgError("派工失败，请重试");
      } finally {
        this.formLoading = false;
      }
    },
    // 强制完结
    doFinished() {
      this.$confirm('确定要强制完结该工单吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        WorkOrderApi.finish(this.pageId).then(response => {
          this.$message.success('强制完结成功');
          this.getList();
        }).catch(error => {
        });
      });
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除生产计划编号为"' + id + '"的数据项?')
      try {
        await PlanApi.deletePlan(id);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    /** 批量删除生产计划 */
    async handleDeleteBatch() {
      await this.$modal.confirm('是否确认删除?')
      try {
        await PlanApi.deletePlanList(this.checkedIds);
        this.checkedIds = [];
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    handleRowCheckboxChange(records) {
      this.checkedIds = records.map((item) => item.id);
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm('是否确认导出所有生产计划数据项?');
      try {
        this.exportLoading = true;
        const data = await PlanApi.exportPlanExcel(this.queryParams);
        this.$download.excel(data, '生产计划.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

/* 工单信息区域样式 */
.work-order-info {
  margin: 20px 0;
}

.info-card {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
  border: 1px solid #e4e7ed;
}

.info-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
  border-color: #409eff;
}

.info-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.info-value {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

/* 质检区域样式 */
.quality-inspection-section {
  margin-top: 30px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 500;
}

/* 分页组件样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 按钮容器样式 */
.button-container {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

/* 每个按钮样式统一 */
.button-container .el-button {
  margin-left: 10px;
}

.button-container .el-button:first-child {
  margin-left: 0;
}

.info-body {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  flex-wrap: wrap;
}

.info-cil {
  width: 25%;
  height: 80px;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding-left: 20px;
}

.info-cil:hover {
  background: #f4f6f8;
}

.info-title {
  font-size: 16px;
}

.info-param {
  margin-top: 5px;
  color: #999;
}
</style>
